import * as R from 'ramda';

import { getUserInfo, getUserMenu } from '@/service/auth';
import { useCallback, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import Cookies from 'js-cookie';
import { DOMAIN } from '../../lib/constants';
import { message } from 'antd';
import { useHistory } from 'react-router-dom';
import { useRequest } from 'ahooks';

const { createSlice } = require('@reduxjs/toolkit');

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    userInfo: null,
    // 菜单树
    menuList: [],
    // 按钮权限列表
    buttonList: [],
  },
  reducers: {
    setUserInfo(state, { payload }) {
      state.userInfo = payload;
    },
    setMenuList(state, { payload }) {
      state.menuList = payload;
    },
    setButtonList(state, { payload }) {
      state.buttonList = payload;
    },
  },
});

export default authSlice;

export const useAuth = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const { userInfo, menuList, buttonList } = useSelector(R.prop('auth'));
  const { loading: getUserInfoLoading, run: fetchUserInfo } = useRequest(
    getUserInfo,
    {
      manual: true,
      throwOnError: true,
      onSuccess: R.compose(
        dispatch,
        authSlice.actions.setUserInfo,
        R.tap(
          R.compose(
            (v) =>
              Cookies.set('uid', v, {
                domain: DOMAIN,
              }),
            R.prop('id'),
          ),
        ),
        R.prop('data'),
      ),
    },
  );

  const { run: fetchMenu, loading: getUserMenuLoading } = useRequest(
    getUserMenu,
    {
      manual: true,
      throwOnError: true,
      onSuccess: (res) => {
        dispatch(authSlice.actions.setMenuList(res?.data.menuList));
        dispatch(authSlice.actions.setButtonList(res?.data.buttonList));
      },
    },
  );

  const bootstrap = useCallback(() => {
    fetchUserInfo();
    fetchMenu();
  }, [fetchUserInfo, fetchMenu]);

  const exit = useCallback(() => {
    message.success('退出成功', 0.5, () => {
      history.replace('/login');
      Cookies.remove('uid', {
        domain: DOMAIN,
      });
      Cookies.remove('token', {
        domain: DOMAIN,
      });
      dispatch(authSlice.actions.setUserInfo(null));
      dispatch(authSlice.actions.setButtonList([]));
      dispatch(authSlice.actions.setMenuList([]));
    });
  }, [dispatch, history]);

  const loading = useMemo(() => {
    if (!userInfo) return true;
    return getUserInfoLoading || getUserMenuLoading;
  }, [userInfo, getUserInfoLoading, getUserMenuLoading]);

  return {
    bootstrap,
    userInfo,
    loading,
    exit,
    menuList,
    buttonList,
  };
};
